import hmac,os
from socket import *
__authoer__='zhuifeng'
ip_port = ("localhost", 1234)
back_log=5
buffsize=1024
connect_key= b'aaaa'
def auth_connect(conn):
    '''验证链接是否合法'''
    print("开始验证链接是否合法")
    msg = os.urandom(32)

    conn.sendall(msg)
    print(msg)
    h = hmac.new(connect_key,msg)
    digest = h.hexdigest() # 十六进制加密
    respone = conn.recv(len(digest))

    print("加密的结果digest",digest.encode("utf-8"))
    print("返回结果respone",respone)
    return hmac.compare_digest(respone,digest.encode("utf-8"))

def data_handle(conn,addr,buffsize):
    '''只处理数据'''
    if not auth_connect(conn):
        print("链接不合法，直接关闭")
        conn.close()
        return
    else:
        print("链接合法，开始发送消息")
    while True:
        data=conn.recv(buffsize)
        if not data:
            break
        print("客户端%s 发来的消息是%s" %(addr,data))
        conn.sendall(data.upper())

def server_handle(ip_port,buffsize):
    '''只处理链接'''
    server_socket=socket(AF_INET,SOCK_STREAM)
    server_socket.bind(ip_port)
    server_socket.listen(back_log)
    while True:
        print("waiting for connect...")
        conn,addr=server_socket.accept()
        print("新链接是：",addr) # addr 是ip与端口组成的元组
        data_handle(conn,addr,buffsize)

if __name__ == '__main__':
    server_handle(ip_port,buffsize)
